package com.yale.spring.cloud.gateway.filter;

import com.yale.spring.cloud.commons.OpenResponse;
import com.yale.spring.cloud.commons.constants.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author yale
 */
@Slf4j
@Component
@RefreshScope
public class WebFilter implements GlobalFilter, Ordered {


    @Autowired
    @Qualifier("ObjectTemplate")
    private RedisTemplate<String,Object> objectRedisTemplate;


    private static final String WELCOME_URL="/api/user/welcome";

    private static final String REGISTRY_URL="/api/user/register";

    private static final String LIMIT_MIN_KEY="limitMin";


    @Value("${registry.limitSec}")
    private Long limitSec;

    @Value("${registry.limitTimes}")
    private Integer limitTimes;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        String uri = request.getPath().pathWithinApplication().value();
        if(uri.startsWith(WELCOME_URL)){
            return chain.filter(exchange);
        }
        if(uri.startsWith(REGISTRY_URL)){
            if(!objectRedisTemplate.hasKey(LIMIT_MIN_KEY)){
                objectRedisTemplate.opsForValue().set(LIMIT_MIN_KEY,1L,limitSec, TimeUnit.SECONDS);
            }else{
                Long increment = objectRedisTemplate.opsForValue().increment(LIMIT_MIN_KEY);
                if(increment > limitTimes){
                    response.setStatusCode(HttpStatus.SEE_OTHER);
                    byte[] bytes = "{\"status\":\"-1\",\"msg\":\"error\"}".getBytes(StandardCharsets.UTF_8);
                    DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
                    return exchange.getResponse().writeWith(Flux.just(buffer));
                }
            }
        }
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        List<HttpCookie> httpCookies = cookies.get(CommonConstants.TOKEN);
        if(httpCookies!=null && objectRedisTemplate.hasKey(httpCookies.get(0).getValue())){
            System.out.println(httpCookies.get(0));
            response.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
            response.getHeaders().set("Location","http://test.com/welcome.html?email="+objectRedisTemplate.opsForValue().get(httpCookies.get(0).getValue()));
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
